package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.order.domain.PayOrder;
import me.zhengjie.modules.order.mapper.PayOrderMapper;
import me.zhengjie.modules.system.domain.req.HomeDetailReq;
import me.zhengjie.modules.system.domain.resp.HomeDetailResp;
import me.zhengjie.modules.system.domain.resp.OrderRevenueResp;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.modules.system.service.AdminCommonService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static me.zhengjie.modules.base.utils.UnitConvertUtil.priceInYuan;
import static me.zhengjie.modules.biz.constant.GlobalConstant.VIP_ORDER;


@Service
@RequiredArgsConstructor
public class AdminCommonServiceImpl implements AdminCommonService {

    private final UserMapper userMapper;
    private final PayOrderMapper payOrderMapper;


    @Override
    public HomeDetailResp home(HomeDetailReq req) {
        HomeDetailResp resp = new HomeDetailResp();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = now.with(LocalTime.MIN);
        LocalDateTime endTime = now.with(LocalTime.MAX);

        List<PayOrder> payOrders = getPayOrders();
        // 总收益
        long totalRevenue = payOrders.stream().mapToLong(PayOrder::getTotal).sum();
        // vip收益
        long vipRevenue = payOrders.stream().filter(order -> order.getOrderType().equals(VIP_ORDER)).mapToLong(PayOrder::getTotal).sum();
        // 当日收益
        long todayRevenue = payOrders.stream()
                .filter(order -> order.getCreateTime().isAfter(startTime) && order.getCreateTime().isBefore(endTime))
                .mapToLong(PayOrder::getTotal)
                .sum();

        resp.setUserNum(userMapper.getUserNum());
        resp.setTotal(payOrders.size());
        resp.setVipRevenue(priceInYuan(vipRevenue));
        resp.setTotalRevenue(priceInYuan(totalRevenue));
        resp.setTodayRevenue(priceInYuan(todayRevenue));
        return resp;
    }


    @Override
    public  List<OrderRevenueResp> timePeriod(HomeDetailReq req) {
        List<OrderRevenueResp> list = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = now.with(LocalTime.MIN);
        LocalDateTime endTime = now.with(LocalTime.MAX);

        List<PayOrder> payOrders = getPayOrders();

        if(req.getStartTime() == null){
            req.setStartTime(startTime);
        }

        if(req.getEndTime() == null){
            req.setEndTime(endTime);
        }

        // 获取时间段中已完成的订单
        List<PayOrder> orderList = payOrders.stream()
                .filter(order -> order.getCreateTime().isAfter(req.getStartTime()) && order.getCreateTime().isBefore(req.getEndTime())).collect(Collectors.toList());

        Map<LocalDate, Double> map = orderList.stream()
                .filter(order -> order.getCreateTime().isAfter(req.getStartTime()) && order.getCreateTime().isBefore(req.getEndTime()))
                .collect(Collectors.groupingBy(order -> order.getCreateTime().toLocalDate(),
                        Collectors.summingDouble(order -> order.getTotal() / 100.0)));

        map.forEach((date, amount) -> {
            OrderRevenueResp resp = new OrderRevenueResp();
            resp.setDate(date);
            resp.setMoney(BigDecimal.valueOf(amount));
            list.add(resp);
        });
        return list;
    }


    /**
     * 获取已交易完成的订单列表
     */
    private List<PayOrder> getPayOrders() {
        return payOrderMapper.selectList(new QueryWrapper<PayOrder>()
                .eq("trade_state", 1)
                .eq("sold_status", 1)
                .isNotNull("transaction_id")
        );
    }

}
